<template>
  <view class="viewport">
    <view class="logo">
      <image src="@/static/images/logo.png"></image>
    </view>
    <view class="login">
      <input v-model="form.mobile" class="input" type="text" placeholder="请输入用户名/手机号码" />
      <input v-model="form.password" class="input" type="text" password placeholder="请输入密码" />
      <input v-model="form.openId" class="input" type="text" placeholder="请输入验证码" hidden />
      <button @tap="onSubmit" class="button phone">登录</button>
    </view>
  </view>
</template>
<script setup lang="ts">
import { postLoginAPI, getLoginWxMinOpenidAPI } from '@/services/login'
import { useMemberStore, useOpenIdStore } from '@/stores'
import type { LoginResult } from '@/types/member'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

// 获取 code 登录凭证
let code = ''
onLoad(async () => {
  getOpenid()
})

// 通过code 获取用户openid

const loginSuccess = (profile: LoginResult) => {
  // 保存会员信息
  const memberStore = useMemberStore()
  memberStore.setProfile(profile)
  // 成功提示
  uni.showToast({ icon: 'success', title: '登录成功' })
  setTimeout(() => {
    // 页面跳转
    uni.switchTab({ url: '/pages/my/my' })
    uni.navigateBack()
  }, 500)
}

const getOpenid = async () => {
  const useOPenId = useOpenIdStore()
  if (useOPenId.openid) {
    const form = {
      mobile: '18147161269',
      password: '222222',
      openId: useOPenId.openid,
    }
    const reslogin = await postLoginAPI(form)
    loginSuccess(reslogin)
    return
  }

  const res = await wx.login()
  code = res.code
  const openIdRes = await getLoginWxMinOpenidAPI(code)
  if (Number(openIdRes.code) === 0) {
    const openId = openIdRes.openId
    useOPenId.setopenId(openId)

    const form = {
      mobile: '18147161269',
      password: '123456',
      openId: openId,
    }
    const reslogin = await postLoginAPI(form)
    if (Number(reslogin.code) == 0) {
      loginSuccess(reslogin)
    }
  }
}
// 传统表单登录，测试账号：13123456789 密码：123456，测试账号仅开发学习使用。
const form = ref({
  mobile: '',
  password: '',
  openId: '',
})
//const useOPenId = useOpenIdStore()

// 表单提交
const onSubmit = async () => {
  const openId = useOpenIdStore()
  form.value.openId = openId.openid

  if (!form.value.openId) {
    uni.showToast({ icon: 'none', title: '没有获取到openId，请稍后再试' })
    return
  }
  const res = await postLoginAPI(form.value)

  if (Number(res.code) == 0) {
    loginSuccess(res)
  } else {
    uni.showToast({ icon: 'none', title: '用户名或者密码错误' })
  }
}
</script>

<style scoped lang="scss">
@import './login.scss';
</style>
